package me.magicall.myblog.base.web.springmvc.interceptors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.magicall.consts.StrConst.UrlConst;
import me.magicall.myblog.front.web.springmvc.controllers.ListController;
import me.magicall.util.Utils;

import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class ReturnViewInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex)
			throws Exception {
	}

	@Override
	public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final ModelAndView modelAndView)
			throws Exception {
		if (modelAndView != null) {
			String viewName = modelAndView.getViewName();
			String uri = request.getRequestURI();
			if (uri.endsWith(UrlConst.URL_SEPERATOR)) {
				uri = uri.substring(0, uri.length() - UrlConst.URL_SEPERATOR.length());
			}
			if (uri.endsWith(viewName)) {
				if (handler != null) {
					if (handler instanceof ListController) {
						final Object modelName = modelAndView.getModelMap().get("modelName");
						if (modelName != null && modelName instanceof String) {
							modelAndView.setViewName("list_" + modelName);
						}
					} else {
						final Controller controller = AnnotationUtils.findAnnotation(handler.getClass(), Controller.class);
						if (controller != null) {
							final String name = controller.value();
							if (!Utils.STR.isEmpty(name)) {
								final int index = name.indexOf("Controller");
								if (index > 0) {
									viewName = name.substring(0, index);
									modelAndView.setViewName(viewName);
								}
							}
						}
					}
				}
			}
		}
	}

	@Override
	public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
		return true;
	}

}
